package cn.tesla_iot.bluetoothchat;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.tesla_iot.chat.video.monitor.R;


//https://blog.csdn.net/xialong_927/article/details/81302948

public class CommActivity extends BaseActivity {

    @BindView(R.id.btn_open_wifispot)
    Button btnOpenWifispot;
    //@BindView(R.id.btn_close_wifispot)
    //Button closeWifiSpot;
    @BindView(R.id.btn_open_wifi)
    Button btnOpenWifi;
    @BindView(R.id.btn_close_wifi)
    Button btnCloseWifi;
    @BindView(R.id.btn_set_wifi)
    Button btnSetWifi;
    @BindView(R.id.btn_disconn_wifi)
    Button btnDisconnWifi;
    @BindView(R.id.commtitle)
    TitleBar titlebar;
    @BindView(R.id.textView)
    TextView textView;

    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    private String connectedDeviceName = "";

    private StringBuffer outStringBuffer;
    private BluetoothAdapter bluetoothAdapter = null;
    private ChatService chatService = null;

    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case ChatService.STATE_CONNECTED:
                            setStatus(getString(R.string.title_connected_to));    //, connectedDeviceName));
                            break;
                        case ChatService.STATE_CONNECTING:
                            setStatus(R.string.title_connecting);
                            break;
                        case ChatService.STATE_LISTEN:
                        case ChatService.STATE_NONE:
                            setStatus(R.string.title_not_connected);
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    //byte[] writeBuf = (byte[]) msg.obj;

                    //String writeMessage = new String(writeBuf);
                    break;
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;

                    String readMessage = new String(readBuf, 0, msg.arg1);
                    System.out.println(connectedDeviceName + ":  " + readMessage);
                    EventBus.getDefault().post(readMessage);
                    //sendMessage("tt");
                    break;
                case MESSAGE_DEVICE_NAME:

                    connectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    Toast.makeText(getApplicationContext(),
                            "Connected to " + connectedDeviceName,
                            Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(),
                            msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
                            .show();
                    break;
            }
            return false;
        }
    });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        titlebar.setTitle("蓝牙通信");
        titlebar.setBackgroundResource(R.color.blue);
        titlebar.setImmersive(true);
        titlebar.setTitleColor(Color.WHITE);

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available",
                    Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.activity_comm;
    }



    private WifiDialog mDialog;

    //自定义的弹窗（提示框）
    public void openWifiSpot() {
        //设备开WIFI热点,蓝牙也不能用了
        final WifiDialog.Builder builder = new WifiDialog.Builder(this);
        builder.setSSID("").setPasswd("")
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mDialog.dismiss();
                }
            })
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                final String ssid = builder.getSSID();
                String passwd = builder.getPWD();

                JSONObject obj = new JSONObject();
                try {
                    obj.put("type", "openwifispot");
                    obj.put("ssid", ssid);
                    obj.put("pwd", passwd);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendMessage(obj.toString());

                /*
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (getSSID(ssid)) {
                            EventBus.getDefault().post(new BluRxBean(54));
                        } else {
                            EventBus.getDefault().post(new BluRxBean(55));
                        }
                    }
                }).start();
                 */

                mDialog.dismiss();
                }
            });
        mDialog = builder.create();
        mDialog.show();
    }


    //自定义的弹窗（提示框）
    public void setWifi() {
        final WifiDialog.Builder builder = new WifiDialog.Builder(this);

        String ssid = getConnWifiSSID();

        builder.setSSID(ssid).setPasswd("")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String ssid = builder.getSSID();
                        String passwd = builder.getPWD();

                        JSONObject obj = new JSONObject();
                        try {
                            obj.put("type", "setwifissidpwd");
                            obj.put("ssid", ssid);
                            obj.put("pwd", passwd);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        sendMessage(obj.toString());


                        mDialog.dismiss();
                    }
                });
        mDialog = builder.create();
        mDialog.show();
    }



    //自定义的弹窗（提示框）
    public void deleteWifi() {
        final WifiDialog.Builder builder = new WifiDialog.Builder(this);

        String ssid = getConnWifiSSID();

        builder.hidePwdView().setSSID(ssid).setPasswd("")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String ssid = builder.getSSID();

                        JSONObject obj = new JSONObject();
                        try {
                            obj.put("type", "disconnectwifi");
                            obj.put("ssid", ssid);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        sendMessage(obj.toString());


                        mDialog.dismiss();
                    }
                });
        mDialog = builder.create();
        mDialog.show();
    }

    public String getConnWifiSSID() {
        WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wm != null) {
            WifiInfo winfo = wm.getConnectionInfo();
            if (winfo != null) {
                String s = winfo.getSSID();
                if (s.length() > 2 && s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
                    return s.substring(1, s.length() - 1);
                }
            }
        }
        return "";
    }

    public List<ScanResult> getWifiList() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        List<ScanResult> scanWifiList = wifiManager.getScanResults();
        List<ScanResult> wifiList = new ArrayList<>();
        if (scanWifiList != null && scanWifiList.size() > 0) {
            HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
            for (int i = 0; i < scanWifiList.size(); i++) {
                ScanResult scanResult = scanWifiList.get(i);
                //Log.e(ConstantUtils.TAG, "搜索的wifi-ssid:" + scanResult.SSID);
                if (!scanResult.SSID.isEmpty()) {
                    String key = scanResult.SSID + " " + scanResult.capabilities;
                    if (!signalStrength.containsKey(key)) {
                        signalStrength.put(key, i);
                        wifiList.add(scanResult);
                    }
                }
            }
        }else {
            //Log.e(ConstantUtils.TAG, "没有搜索到wifi");
        }
        return wifiList;
    }

    public boolean getSSID(String ssid) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        List<ScanResult> scanWifiList = wifiManager.getScanResults();
        List<ScanResult> wifiList = new ArrayList<>();
        if (scanWifiList != null && scanWifiList.size() > 0) {
            HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
            for (int i = 0; i < scanWifiList.size(); i++) {
                ScanResult scanResult = scanWifiList.get(i);
                //Log.e(ConstantUtils.TAG, "搜索的wifi-ssid:" + scanResult.SSID);
                if (!scanResult.SSID.isEmpty()) {
                    if (scanResult.SSID.equals(ssid))
                        return true;
                }
            }
        }else {
            //Log.e(ConstantUtils.TAG, "没有搜索到wifi");
            return false;
        }
        return false;
    }


    @OnClick({R.id.btn_open_wifispot, R.id.btn_open_wifi, R.id.btn_close_wifi, R.id.btn_set_wifi, R.id.btn_disconn_wifi})
    public void onViewClicked(View view) {
        JSONObject obj = new JSONObject();
        switch (view.getId()) {
            case R.id.btn_open_wifispot:
                openWifiSpot();
                break;
                /*
            case R.id.btn_close_wifispot:
                try {
                    obj.put("type", "closewifispot");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                SendSocketService.sendMessage(obj.toString());
                break;
                 */
            case R.id.btn_open_wifi:
                try {
                    obj.put("type", "openwifi");
                    obj.put("ssid", "freewifi");
                    obj.put("pwd", "987654321");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendMessage(obj.toString());
                break;
            case R.id.btn_close_wifi:
                try {
                    obj.put("type", "closewifi");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendMessage(obj.toString());
                break;
            case R.id.btn_set_wifi:
                setWifi();
                break;
            case R.id.btn_disconn_wifi:
                deleteWifi();
                /*
                try {
                    obj.put("type", "disconnectwifi");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                SendSocketService.sendMessage(obj.toString());
                */

                break;
        }
    }




    private void connectDevice(Intent data, boolean secure) {
        String address = data.getExtras().getString(
                DeviceListActivity.DEVICE_ADDRESS);
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
        chatService.connect(device, secure);
    }

    private void sendMessage(String message) {
        if (chatService.getState() != ChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        if (message.length() > 0) {
            byte[] send = message.getBytes();
            chatService.write(send);

            outStringBuffer.setLength(0);
        }
    }


    private final void setStatus(int resId) {
        textView.setText(resId);
    }

    private final void setStatus(CharSequence subTitle) {
        textView.setText(subTitle);
    }

    private void setupChat() {
        chatService = new ChatService(this, handler);

        outStringBuffer = new StringBuffer("");
    }

    @Override
    public void onStart() {
        super.onStart();

        if (!bluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if (chatService == null)
                setupChat();
            //connectDevice(data, true);
            connectDevice(getIntent(), true);
        }


    }

    @Override
    public synchronized void onResume() {
        super.onResume();

        if (chatService != null) {
            if (chatService.getState() == ChatService.STATE_NONE) {
                chatService.start();
            }
        }
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
        if (chatService != null)
            chatService.stop();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }
}
